<?php
class ApisController extends AppController{
	public $uses = array('User','Tweet','FollowUser','TweetBox','BlockUser','TweetFavorite');
	
	function login(){
		//$this->autoRender = false;
		if($this->request->is('post')){
			$arr = $this->request->data;
			return ($this->User->login($arr['uname'],$arr['pass']));
		}
	}
	
	function search_user(){
		//$this->autoRender = false;
		if($this->request->is('post')){
			if(!isset($arrData['page_index']))
				$index = 1;
			else $index = $arrData['page_index'];
			$arr = $this->request->data;
			//debug($this->User->search($arr['uname'],$arr['uid']),$index);	
			return ($this->User->search($arr['uname'],$arr['uid'],$index));
		}
	}
	
	function get_user_detail(){
		//$this->autoRender = false;
		if($this->request->is('post')){
			$arr = $this->request->data;
			if($this->FollowUser->findByUserIdAndUserIdFollowed($arr['uid'],$arr['uname']))
				return ($this->User->getDetail($arr['uname']));
			else if($arr['uid'] == $arr['uname']){
				return ($this->User->getDetail($arr['uname']));
			}
			else return json_encode(array('is_success'=>false,'message'=>'can not access'));
		}
	}
	function post_tweet(){
		//$this->autoRender = false;
		if($this->request->is('post')){
			$this->Tweet->unbindModel(array('hasMany'=>array('TweetBox','TweetTag','TweetMention','TweetUrl','TweetFavorite')),false);
			$this->User->unbindModel(array('hasMany'=>array('TweetBox','Tweet','TweetFavorite','BlockUser','FollowUser')),false);
			$arrData = $this->request->data;
//			debug($arrData);die;
			return $this->_saveTweet($arrData,false);
			}else return json_encode(array( 'is_success'=>false,
								  	  		'message'=>'not support this type',
								  	  		'tweet'=>null));
		return json_encode(array('im not ok'));
	}
	
	function get_timeline(){
//		debug($_SERVER['HTTP_USER_AGENT']);die('here');
		//$this->autoRender = false;
		if($this->request->is('post')){
			$arrData = $this->request->data;
			if(!isset($arrData['page_index']))
				$index = 1;
			else $index = $arrData['page_index'];
			$this->TweetBox->unbindModel(array('belongsTo'=>array('User')),false);
			$tweet = $this->TweetBox->find('all',array('conditions'=>array('TweetBox.user_id'=>$arrData['user_id']),
													   'offset'=>($index-1) * MAX_TWEET_PER_PAGE,
													   'limit'=>MAX_TWEET_PER_PAGE,
													   'order'=>array('TweetBox.created DESC')));
			
			$this->User->unbindModel(array('hasMany'=>array('TweetBox','Tweet','TweetFavorite','BlockUser','FollowUser')),true);
			for($i=0;$i<count($tweet);$i++){
					$user = $this->User->findById($tweet[$i]['Tweet']['user_id']);
					$tweet[$i]['User'] = $user['User'];
					$tweet[$i]['create_ago'] = $this->_secondToTime(strtotime(date("Y-m-d H:i:s")) - strtotime($tweet[$i]['Tweet']['created']));
					if($tweet[$i]['TweetBox']['retweet'] == 1)
						$tweet[$i]['TweetBox']['is_retweet'] = "yes";
					else $tweet[$i]['TweetBox']['is_retweet'] = "no";
					
					$tweet[$i]['total_parent'] = $this->Tweet->get_parent($tweet[$i]['TweetBox']['tweet_id']);
					
					$this->TweetFavorite->unbindModel(array('belongsTo'=>array('User','Tweet')));
					
					if($this->TweetFavorite->find('first',array('conditions'=>array('user_id'=>$arrData['user_id'],
																					'tweet_id'=>$tweet[$i]['TweetBox']['tweet_id'],
																					'untweet_flag'=>1))))
						$tweet[$i]['TweetBox']['is_favorite'] = "yes";
					else $tweet[$i]['TweetBox']['is_favorite'] = "no";
					
					if($reply = $this->Tweet->getReply($tweet[$i]['TweetBox']['tweet_id'])){
						for ($j=0;$j<count($reply);$j++){
							$reply[$j]['create_ago'] = $this->_secondToTime(strtotime(date("Y-m-d H:i:s")) - strtotime($reply[$j]['Tweet']['created']));
							$tweet[$i]['Reply'][$j] = $reply[$j];
						}
					}
			}
			return json_encode($tweet);
//			debug($tweet);
		}
	}
	
	function block_user(){
		//$this->autoRender = false;
		if($this->request->is('post')){
			$arrData = $this->request->data;
			if($isExisted = $this->BlockUser->findByUserIdAndUserIdBlocked($arrData['user_id'],$arrData['blocker_id'])){
				$this->BlockUser->id = $isExisted['BlockUser']['id'];
				$this->BlockUser->saveField('block_flg',$arrData['is_block']);
			}else{
				$this->BlockUser->create();
				$arrSave['user_id'] = $arrData['user_id'];
				$arrSave['user_id_blocked'] = $arrData['blocker_id'];
				$arrSave['block_flg'] = $arrData['is_block'];
				$this->BlockUser->set($arrSave);
				$this->BlockUser->save();
			}
		}
	}
	//begin duchv//
	function signup(){
		//$this->autoRender = false;
		if (!empty($this->data)) {
			//debug($this->data);
			$this->User->create();
			if ($this->User->save($this->data)) {
				//$this->Session->setFlash(__('The user has been saved', true));
				//$this->redirect(array('action' => 'index'));
				return json_encode(array('is_success'=>true,
						'message'=>'The user has been saved'));
			} else {
				//$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
				return json_encode(array('is_success'=>false,
						'message'=>'The user could not be saved. Please, try again.'));
			}
		}
	
	}
	
function edituser(){
		//$this->autoRender = false;
		if (!empty($this->data)) {
			//debug($this->data);
			$arr=$this->data;
			if(empty($arr['id']))
			{
				$this->User->create();
				if ($this->User->save($this->data)) {
					return json_encode(array('is_success'=>true,
							'message'=>'The user has been saved'));
				} else {
					return json_encode(array('is_success'=>false,
							'message'=>'The user could not be saved. Please, try again.'));
				}
			}else {
				//debug($arr['id']);
				$this->User->id =$arr['id'];
				if ($this->User->save($this->data)) {
					return json_encode(array('is_success'=>true,
							'message'=>'The user has been saved'));
				} else {
					return json_encode(array('is_success'=>false,
							'message'=>'The user could not be saved. Please, try again.'));
				}
	
			}
		}
	
	}
	
	function reg_follow(){
		//$this->autoRender = false;
//		echo json_encode('ok');die;
		if($this->request->is('post')){
			$this->Tweet->unbindModel(array('hasMany'=>array('TweetBox','TweetTag','TweetMention','TweetUrl','TweetFavorite')),false);
			$this->User->unbindModel(array('hasMany'=>array('TweetBox','Tweet','TweetFavorite','BlockUser','FollowUser')),false);
			//$this->FollowUser->unbindModel(array('hasMany'=>array()));
			$arrData = $this->request->data;
			$hastweet = $this->Tweet->find('all',array( 'conditions' => array('Tweet.user_id =' => $arrData['following_user_id']),
														'fields'=>array("id")));
			//debug($hastweet);die("asdasdas");
			$ishas = $this->FollowUser->findByUserIdAndUserIdFollowed($arrData['user_id'],$arrData['following_user_id']);
			//debug('here1');
			if($arrData['isFollowing'] == 1){
	
				if(!$ishas )
				{
					$this ->FollowUser ->create();
					$arrSave['user_id'] = $arrData['user_id'];
					$arrSave['user_id_followed'] = $arrData['following_user_id'];
					$arrSave['follow_at'] =date('Y-m-d h:i:s');
					//debug($arrSave);
					$this->FollowUser->set($arrSave);
					$this->FollowUser->save();
					echo json_encode(array('is_success'=> true,'message' =>'followed','result'=> '1'));
					if(!empty($hastweet)){
						foreach ($hastweet as $tw){
							//debug('here3');
							$this->TweetBox->create();
							$this->TweetBox->set(array('tweet_id'=>$tw['Tweet']['id'],
									'user_id'=>$arrData['user_id'],'retweet' => false));
							$this->TweetBox->save();
						}
					}
					
				}else 	return json_encode(array('is_success'=> true,'message' =>'had been this follow'));
					
	
			}else{
				//debug($arrData);
	
				if($ishas){
					$this->FollowUser->delete($ishas['FollowUser']['id'],false);
					echo json_encode(array('is_success'=> true,'message' =>'unfollowed','result'=> '0'));
					//$this->FollowUser->save();
					if(!empty($hastweet)){
						foreach ($hastweet as $tw){
								
							//$condition = array('tweet_id' =>$tw['Tweet']['id'],'user_id'=>$arrData['user_id']);
							//debug($condition);die("asdasd");
							$dtw = $this->TweetBox->findByTweetIdAndUserId($tw['Tweet']['id'],$arrData['user_id']);
							//debug($dtw);
							$this->TweetBox->delete($dtw['TweetBox']['id']);
								
						}
					}
					
				}else{
					return json_encode(array('is_success'=> false,'message' =>'action false'));
				}
			}
		}
	}
	
	function delete_tweet(){
		//$this->autoRender = false;
		if($this->request->is('post')){
			$arrData = $this->request->data;
			$is = $this->Tweet->findById($arrData['tweet_id']);
			$own = $this->Tweet->findByIdAndUserId($arrData['tweet_id'],$arrData['user_id']);
			if($is)
				if($own){
				$this->Tweet->delete($arrData['tweet_id'],true);
				return json_encode(array('is_success'=>true,'message'=>'have deleted'));
			}else 	return json_encode(array('is_success'=>false,'message'=>'have not permission'));
		}
	}
function re_tweet(){
		//$this->autoRender = false;
		if($this->request->is('post')){
		$arrData = $this->request->data;
		$iss = $this->TweetBox->findByTweetIdAndUserId($arrData['tweet_id'],$arrData['user_id']);
		if($iss){
			$this -> TweetBox->id = $iss['TweetBox']['id'];
			$arrSave['user_id'] = $arrData['user_id'];
			$arrSave['tweet_id'] = $arrData['tweet_id'];
			//$arrSave['creat_at'] =date('Y-m-d h:i:s');
			$arrSave['retweet'] = true;
			//debug($arrSave);
			if($this -> TweetBox->save($arrSave));
			{
				$folow = $this->FollowUser->find('all',array('conditions'=>array('user_id_followed'=>$arrData['user_id']),'fields'=>array('user_id')));
				foreach ($folow as $fo){
					$ishas = $this->TweetBox->findByTweetIdAndUserId($arrData['tweet_id'],$fo['FollowUser']['user_id']);
					//debug($ihas);
					if(!$ishas){
					$this->TweetBox->create();
					$arrCr['user_id'] = $fo['FollowUser']['user_id'];
					$arrCr['tweet_id'] = $arrData['tweet_id'];
					//$arrSave['creat_at'] =date('Y-m-d h:i:s');
					$arrCr['retweet'] = false;
				$this->TweetBox->save($arrCr);
					}
				}
			//$tweet = $this->Tweet->findById($arrData['twee_id']);
			
			//debug($tweet);
			return json_encode(array('is_success'=>true,
					'message'=>'success'));
			}
		}else return json_encode(array('is_success'=>false,
					'message'=>'this tweet have not existed'));
	  }
	}
function favorite()
	{
		//$this->autoRender = false;
		if($this->request->is('post')){
		$arrData = $this->request->data;
		//$condition = array('tweet_id'=>$arrdatar['tweet_id'],'user_id'=>$arrdata['user_id']);
		$iss = $this->TweetBox->findByTweetId($arrData['tweet_id']);
		$is = $this->TweetFavorite->findByTweetIdAndUserId($arrData['tweet_id'],$arrData['user_id']);
		//debug($iss);
		if($iss){
		
				if(!$is){
					if($arrData['acction'] ==1){
				$this -> TweetFavorite->create();
				$arrSave['user_id'] = $arrData['user_id'];
				$arrSave['tweet_id'] = $arrData['tweet_id'];
				$arrSave['creat_at'] =date('Y-m-d h:i:s');
				$arrSave['untweet_flag'] = $arrData['acction'];
				//debug($arrSave);
				$this -> TweetFavorite->save($arrSave);
				return json_encode(array('is_success'=>true,'message'=>'success','isfav'=>($arrSave['untweet_flag']==1)));
			}else return json_encode(array('is_success'=>false,'message'=>"acction failed"));
			
		}elseif($is){
			//debug($is);
			$this -> TweetFavorite->read(null,$is['TweetFavorite']['id']);
// 			$arrSave['user_id'] = $arrData['user_id'];
// 			$arrSave['tweet_id'] = $arrData['tweet_id'];
// 			$arrSave['creat_at'] =date('Y-m-d h:i:s');
// 			$arrSave['untweet_flag'] = $arrData['acction'];
			//debug($arrSave);
			$this->TweetFavorite->set('untweet_flag',$arrData['acction']);
			$this ->TweetFavorite->save();
			return json_encode(array('is_success'=>true,'message'=>'success','isfav'=>$arrData['acction']));
		}
		else return json_encode(array('is_success'=>false,'message'=>'acction failed'));
		}else return json_encode(array('is_success'=>false,'message'=>'acction failed'));
	}
	}
	
	
function get_list_favorite(){
		//$this->autoRender = false;
		if($this->request->is('post')){
			$arrData = $this->request->data;
			$this->TweetFavorite->unbindModel(array('belongsTo'=>array('User')),false);
			if(isset($arrData['page_index']))
				$index = $arrData['page_index'];
			else $index = 1;
			//$this->User->unbindModel(array('hasMany'=>array('TweetBox','Tweet','TweetFavorite','BlockUser','FollowUser')),false);
			//$fo = $this->FollowUser->findByUserIdFollowedAndUserId($arrData['user_id'],$arrData['viewed_user_id']);
			$fav = $this->TweetFavorite->find('all',array('conditions'=>array('TweetFavorite.user_id'=>$arrData['user_id'],'untweet_flag' =>1),'offset'=>($index-1)*MAX_TWEET_PER_PAGE,
														  'limit'=>MAX_TWEET_PER_PAGE));
			// Do da thuc hien khai bao be long va has many tai model nen khi serach nhu tren tweet se duoc day ra toan bo
			//debug($fav);
			for ($i=0;$i<count($fav);$i++)
				unset($fav[$i]['TweetFavorite']);
			//if($fo){
			//debug($fav);
			//echo (json_encode($fav));
				return json_encode($fav);
				
			//}
			//else return(array('is_success' => false,'message'=>'have not existed'));
		}
		else return(array('is_success' => false,'message'=>'acction failed'));
	}
	
	function get_list_user_favorite(){
		//$this->autoRender = false;
		if($this->request->is('post')){
			$arrData = $this->request->data;
			$this->TweetFavorite->unbindModel(array('belongsTo'=>array('Tweet')),false);
			if(isset($arrData['page_index']))
				$index = $arrData['page_index'];
			else $index = 1;
			$fav = $this->TweetFavorite->find('all',array('conditions'=>array('TweetFavorite.tweet_id'=>$arrData['tweet_id'],'untweet_flag' =>1),'offset'=>($index-1)*MAX_TWEET_PER_PAGE,
					'limit'=>MAX_TWEET_PER_PAGE));
			// Do da thuc hien khai bao be long va has many tai model nen khi serach nhu tren tweet se duoc day ra toan bo
			//debug($fav);
			for ($i=0;$i<count($fav);$i++)
				unset($fav[$i]['TweetFavorite']);
				//if($fo){
			//debug($fav);
				//echo (json_encode($fav));
				return json_encode($fav);
	
				//}
				//else return(array('is_success' => false,'message'=>'have not existed'));
		}
		else return(array('is_success' => false,'message'=>'acction failed'));
	}
	
	
	function get_list_followed(){
		//$this->autoRender = false;
		if($this->request->is('post')){
			$arrData = $this->request->data;
			if(isset($arrData['page_index']))
				$index = $arrData['page_index'];
			else $index = 1;
			$listFld = $this->FollowUser->find('all',array('conditions'=>array('user_id_followed'=>$arrData['user_id']),
					'fields'=>array('user_id'),
					'offset'=>($index-1)*MAX_TWEET_PER_PAGE,
					'limit'=>MAX_TWEET_PER_PAGE));
			//			debug($listFl);
			$this->User->unbindModel(array('hasMany'=>array('TweetBox','Tweet','TweetFavorite','BlockUser','FollowUser')),true);
			for ($i=0;$i<count($listFld);$i++){
				$user = $this->User->findById($listFld[$i]['FollowUser']['user_id']);
				$listFld[$i]['User'] = $user['User'];
				if($this->FollowUser->findByUserIdAndUserIdFollowed($listFld[$i]['FollowUser']['user_id'],$arrData['user_id'])){
					$listFld[$i]['is_follwed'] = 'yes';
				}else $listFld[$i]['is_follwed'] = 'no';
			}
			//			debug($listFl);
			return json_encode($listFld);
		}
	}
	function count_list_follow(){
		//$this->autoRender = false;
		if($this->request->is('post')){
			$arrData = $this->request->data;
			$countfl = $this->FollowUser->find('count',array('conditions'=>array('user_id'=>$arrData['user_id'])));	
			return json_encode($countfl);
		}
	}
	
	
function view_con(){
		//$this->autoRender = false;
		if($this->request->is('post')){
			$arrData = $this->request->data;
			if(isset($arrData['page_index']))
				$index = $arrData['page_index'];
			else $index = 1;
			$listRep = $this->Tweet->find('all',array('conditions'=>array('Tweet.paren_id'=>$arrData['tweet_id']),
					//'fields'=>array('id'),
					'offset'=>($index-1)*MAX_TWEET_PER_PAGE,
					'limit'=>MAX_TWEET_PER_PAGE));
			//			debug($listFl);
			$this->Tweet->unbindModel(array('hasMany'=>array('TweetBox','TweetTag','TweetMention','TweetUrl','TweetFavorite')),false);
			
			//			debug($listFl);
			return json_encode($listRep);
		}
	}
	
	//     end duchv            //
	function get_list_follow(){
		//$this->autoRender = false;
		if($this->request->is('post')){
			$arrData = $this->request->data;
			if(isset($arrData['page_index']))
				$index = $arrData['page_index'];
			else $index = 1;
			$listFl = $this->FollowUser->find('all',array('conditions'=>array('user_id'=>$arrData['user_id']),
													  	  'fields'=>array('user_id_followed'),
														  'offset'=>($index-1)*MAX_TWEET_PER_PAGE,
														  'limit'=>MAX_TWEET_PER_PAGE));
			$this->User->unbindModel(array('hasMany'=>array('TweetBox','Tweet','TweetFavorite','BlockUser','FollowUser')),true);
			for ($i=0;$i<count($listFl);$i++){
				$user = $this->User->findById($listFl[$i]['FollowUser']['user_id_followed']);
				$listFl[$i]['User'] = $user['User'];
			}
			return json_encode($listFl);
		}
	}
	
	
	function upload(){
		//$this->autoRender = false;
			/*
		Uploadify
		Copyright (c) 2012 Reactive Apps, Ronnie Garcia
		Released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
		*/
		if($this->request->is('post')){
//			debug($_FILES);die;
			// Define a destination
			$arrData = $this->request->data;
			$targetFolder = IMG_UPLOAD_URL; // Relative to the root
			$targetUrl = SITE_URL.'twister-lite/img/upload';
			if (!empty($_FILES)) {
				$tempFile = $_FILES['image_file']['tmp_name'];
				$targetFile = rtrim($targetFolder,'/') . '/' . basename($_FILES['image_file']['name']);
				
				// Validate the file type
				$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
				$fileParts = pathinfo($_FILES['image_file']['name']);
				
				if (in_array($fileParts['extension'],$fileTypes)) {
					move_uploaded_file($tempFile,$targetFile);
					//decode64
					$ifp = fopen($targetFile,'rb');
					$srcData = fread( $ifp, filesize( $targetFile )); 
					fclose($ifp);
//					$randomName = substr( str_shuffle( 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' ) , 0 , rand(35,50) ).'.'.$fileParts['extension'];
					$randomName = $arrData['media_url'].'.'.$fileParts['extension'];
					$newFile = $targetFolder.'/'.$randomName;
					$ifp2 = fopen($newFile , "wb+" );
				  	fwrite( $ifp2, base64_decode( $srcData ) ); 
				  	fclose( $ifp2 );
				  	//end of decode64
				  	unlink($targetFile);
					return json_encode(array('image_url'=>$targetUrl.'/'.$randomName,
											 'size'=>getimagesize($targetUrl.'/'.$randomName)));
				} else {
					return json_encode('false1');
				}
			}else return json_encode('false2');
		}else return json_encode('false3');
	}
	
	function reply_text(){
		//$this->autoRender = false;
		if($this->request->is('post')){
			$arrData = $this->request->data;
			return $this->_saveTweet($arrData,true);
		}else return json_encode(array( 'is_success'=>false,
								  	  	'message'=>'not support this type',
								  	  	'tweet'=>null));
	}
	
	function _saveTweet($arrData,$isTweet = false){
//			debug($arrData);die;
			if($this->User->findById((int)$arrData['user_id'])){
				//debug('here');
				$arrSave['user_id'] = (int)$arrData['user_id'];
				$arrSave['tweet_text'] = utf8_encode($arrData['text']);
				if(isset($arrData['link_image']))
					$arrSave['media_url'] = $arrData['link_image'];
				if($isTweet)
					$arrSave['parent_id'] = $arrData['parent_id'];
				/*
				$arrSave['geo_long'] = $arrData['longtitude'];
				$arrSave['geo_lat'] = $arrData['latitude'];
				//*/
				$this->Tweet->id = null;
				$this->Tweet->set($arrSave);
				if($tweet = $this->Tweet->save()){
					//debug('here2');
					$conditionsUserFollow = array('conditions'=>array('user_id_followed'=>$arrSave['user_id']),
									  			  'fields'=>array('user_id'));
					$arrUserFollow = $this->FollowUser->find('all',$conditionsUserFollow);
					$this->TweetBox->id=null;
					$this->TweetBox->set(array('tweet_id'=>$tweet['Tweet']['id'],
											   'user_id'=>$arrSave['user_id']));
					$this->TweetBox->save();
					if(!empty($arrUserFollow)){
						foreach ($arrUserFollow as $follow){
							//debug('here3');
							$this->TweetBox->create();
							$this->TweetBox->set(array('tweet_id'=>$tweet['Tweet']['id'],
													   'user_id'=>$follow['FollowUser']['user_id']));
							$this->TweetBox->save();
						}
					}
					
					return json_encode(array('is_success'=>true,
											 'message'=>'success',
											 'tweet'=>$tweet));
				}
			}
			return json_encode(array( 'is_success'=>false,
								  	  'message'=>'failure',
								  	  'Tweet'=>null));
	}
	
	function _secondToTime($seconds){
//		debug($seconds);die;
		$year = (int)($seconds / (60*60*24*30*12));
		if($year >0)
			return $year." year(s) ago";
		else{
			$month = (int)(($seconds/(60*60*24*30)) - ($year*12));
			if($month > 0)
				return $month." month(s) ago";
			else{
				$day = (int)(($seconds/(60*60*24)) - ($month*30));
				if($day >0)
					return $day." day(s) ago";
				else{ 
				$hours = (int)(($seconds /(60*60))-($day*24));
				if($hours >0)
					return $hours." hour(s) ago";
				else{
					$mins = (int)(($seconds - ($hours*3600)) / 60);
					if($mins >0)
						return $mins." minute(s) ago";
					else{
						return $seconds." second(s) ago";
						}
					}
				}
			}
		}
	}
	
		
	function get_timeline_detail(){
		//$this->autoRender = false;
		if($this->request->is('post')){
			$t_id = $this->request->data['tweet_id'];
			$u_id = $this->request->data['user_id'];
			return $this->Tweet->get_tweet_detail($t_id,$u_id);
		}
	}
	
	function get_favorite_detail(){
		//$this->autoRender = false;
		if($this->request->is('post')){
			$arrData = $this->request->data;
			$this->TweetFavorite->unbindModel(array('belongsTo'=>array('Tweet')));
			$list_favorites = $this->TweetFavorite->find('all',array('conditions'=>array('tweet_id'=>$arrData['tweet_id'],
																						 'untweet_flag !='=>1),
																	 'offset'=>($arrData['page_index']-1),
																	 'limit'=>(MAX_TWEET_PER_PAGE)));
//			$isFavorite = $this->TweetFavorite->findByUserIdAndTweetId($arrData['user_id'],$arrData['tweet_id']);
			if($list_favorites){
				for ($i=0;$i<count($list_favorites);$i++){
					if($this->FollowUser->findByUserIdAndUserIdFollowed($arrData['user_id'],$list_favorites[$i]['TweetFavorite']['user_id'])){
						$list_favorites[$i]['TweetFavorite']['is_follwed'] = 'yes';
					}else $list_favorites[$i]['TweetFavorite']['is_follwed'] = 'no';
				}
//				if($isFavorite)
//					$list_favorites['is_favorite'] = "yes";
//				else $list_favorites['is_favorite'] = "no";
				return json_encode($list_favorites);
			}else return json_encode(array("Not found"));
		}
	}	
	
	function get_retweet_detail(){
		//$this->autoRender = false;
		if($this->request->is('post')){
			$arrData = $this->request->data;
			$this->TweetBox->unbindModel(array('belongsTo'=>array('Tweet')));
			$list_retweet = $this->TweetBox->find('all',array('conditions'=>array('tweet_id'=>$arrData['tweet_id'],
																				  'retweet'=>1),
															  'offset'=>($arrData['page_index']-1),
															  'limit'=>(MAX_TWEET_PER_PAGE)));
			if($list_retweet){
				for ($i=0;$i<count($list_retweet);$i++){
					if($this->FollowUser->findByUserIdAndUserIdFollowed($arrData['user_id'],$list_retweet[$i]['TweetFavorite']['user_id'])){
						$list_retweet[$i]['TweetBox']['is_follwed'] = 'yes';
					}else $list_retweet[$i]['TweetBox']['is_follwed'] = 'no';
				}
				return json_encode($list_retweet);
			}else return json_encode(array("Not found"));
		}
	}
	
	function get_reply_detail(){
		//$this->autoRender = false;
		if($this->request->is('post')){
			$arrData = $this->request->data;
			$list_reply = $this->Tweet->find('all',array('conditions'=>array('parent_id'=>$arrData['tweet_id']),
														 'offset'=>($arrData['page_index']-1),
														 'limit'=>(MAX_TWEET_PER_PAGE)));
			if($list_reply)
				return json_encode($list_reply);
			else return json_encode(array("Not found"));
		}
	}
	
	function auto_complete(){
		//$this->autoRender = false;
		if($this->request->is('post')){
			$key = $this->request->data['key'];
			$u_id = $this->request->data['user_id'];
			return json_encode($this->User->query("SELECT DISTINCT User.* FROM `follow_users` AS `FollowUser` LEFT JOIN `users` AS `User` ON (`FollowUser`.`user_id_followed` = `User`.`id`  AND `FollowUser`.`user_id` = {$u_id}) WHERE `User`.`nick_name` LIKE '%{$key}%'"));
		}
	}
	
	function get_own_tweet(){
	    //$this->autoRender = false;
		if($this->request->is('post')){
			$arrData = $this->request->data;
			$this->Tweet->unbindModel(array('hasMany'=>array('TweetBox','TweetTag','TweetMention','TweetUrl','TweetFavorite')),false);
				
			if(!isset($arrData['page_index']))
				$index = 1;
			else $index = $arrData['page_index'];
			$this->Tweet->unbindModel(array('belongsTo'=>array('User')),false);
			$tweet = $this->Tweet->find('all',array('conditions'=>array('Tweet.user_id'=>$arrData['user_id']),
													   'offset'=>($index-1) * 16,
													   'limit'=>16,
													   'order'=>array('Tweet.created DESC')));
			
			$this->User->unbindModel(array('hasMany'=>array('TweetBox','TweetTag','TweetMention','TweetUrl','TweetFavorite','Tweet','BlockUser','FollowUser')),false); 
			$this->TweetBox->unbindModel(array('belongsTo'=>array('User')),false);
			$retweet = $this->TweetBox->find('all',array('conditions'=>array('TweetBox.user_id'=>$arrData['user_id'],'retweet'=>1),
					'offset'=>($index-1) * 4,
					'limit'=>4));
			//debug($retweet);
			if($retweet)
			for($i=0;$i<count($retweet);$i++){
				unset($retweet[$i]['TweetBox']);
				$retweet[$i]['User'] = $this->User->findById($retweet[$i]['Tweet']['user_id']);
			}
			//debug($retweet);
			foreach($tweet as $arr){
				$retweet[] = $arr;
			}
			//debug($tweet);
			return json_encode($retweet);
//			debug($tweet);
		}
	}
	
	function testSS(){
		debug($this->User->query("SELECT DISTINCT User.* FROM `follow_users` AS `FollowUser` LEFT JOIN `users` AS `User` ON (`FollowUser`.`user_id_followed` = `User`.`id`  AND `FollowUser`.`user_id` = 1) WHERE `User`.`nick_name` LIKE '%one%'"));
	}
}